import { useStore } from '@/hooks';
import { Form, Dialog, ResponsiveGrid, Button } from '@alifd/next';
import { t } from '@lingui/macro';
import { toJS } from 'mobx';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../stores/definitions';
import TicketTable from './TicketTable';
import DrawerFooter from '@/components/DrawerFooter';
import TauTable from '@/components/TauTable';
import styles from './RsOrderForm.module.scss';

const FormItem = Form.Item;
const { Cell } = ResponsiveGrid;

const RsOrderForm = (props) => {
  const {
    modal,
    onCancel,
    orderId,
    onSubmit,
  } = props;
  const { rsOrderStore: store } = useStore();
  const [order, setOrder] = useState();
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current;

  useEffect(() => {
    if (modal[1]?.startsWith?.('toClose')) handleCancel();
  }, [modal]);

  useEffect(() => {
    (async () => {
      const data = await store.get(orderId);
      editCtx.origin = _.cloneDeep(data);
      setOrder(toJS(data));
    })();
  }, []);

  if (!order) return <></>;

  const overrideModel = {
    discountInfos: {
      ui: {
        renderer: (v) => {
          return (
            <TauTable
              dataSource={v}
              primaryKey="couponId"
              hidePagination
              hasBorder={false}
              className={styles.discountInfos_table}
              columns={[
                { title: '活动名称', dataIndex: 'activityName' },
                { title: '活动Id', dataIndex: 'activityId' },
                { title: '优惠券名称', dataIndex: 'couponName' },
                { title: '优惠券Id', dataIndex: 'couponId' },
                { title: '优惠券金额', dataIndex: 'discountPrice' },
                { title: '优惠券成本', dataIndex: 'cost' },
              ]}
            />
          );
        },
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(order, name, value);
    setOrder({ ...order });

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    if (!_.isEmpty(editCtx.changed)) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <>
      <Form
        inline
        isPreview={isViewMode}
        {...formProps}
        value={order}
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <TitleGrid title={t`基本信息`} />
        <FieldsGrid
          formData={order}
          mode="view"
          fields={[
            'orderNumber',
            'rsOrder.payTime',
            'rsOrder.orderStatus',
            'rsOrder.payType',
            'price',
            'discountPriceTotal',
            'source',
            'attributionName',
            'receiveName',
            // 'writeOffUserName',
            // 'rsOrder.ticketInfo[0].writeOffDate',
            'companyName',
            // 'operatingCompanyName',
          ]}
        />
        <TitleGrid title={t`优惠信息`} />
        <FieldsGrid
          formData={order}
          mode="view"
          overrideModel={overrideModel}
          fields={[
            'discountInfos',
          ]}
        />
        <TitleGrid title={t`客户资料`} />
        <FieldsGrid
          formData={order}
          mode="view"
          fields={[
            'rsOrder.passengerName',
            'rsOrder.passengerPhone',
            // 'rsOrder.subrsribeName',
            // 'rsOrder.subrsribePhone',
          ]}
        />
        <TitleGrid title={t`预定信息`} />
        <FieldsGrid
          formData={order}
          mode="view"
          fields={[
            'rsOrder.startMainAreaText',
            'rsOrder.endMainAreaText',
            'rsOrder.startStationName',
            'rsOrder.endStationName',
            'rsOrder.beginName',
            'rsOrder.endName',
            'rsOrder.predictBeginDate',
          ]}
        />
        <TitleGrid title={t`车票信息`} />
        <ResponsiveGrid gap={[0, 24]} columns={4}>
          <Cell colSpan={12}>
            <TicketTable
              rsOrder={order?.rsOrder}
              inForm
              isViewMode={isViewMode}
              refundInfos={order?.refundInfos}
            />
          </Cell>
        </ResponsiveGrid>
        <TitleGrid title={t`备注`} />
        <FieldsGrid
          formData={order}
          mode={modal[0]}
          fields={[
            'rsOrder.remarks',
            'orderChangeRemarks',
            // 'rsOrder.consoleRemarks',
          ]}
        />
        <DrawerFooter>
          <FormItem>
            {!isViewMode && (
              <Form.Submit
                validate
                type="primary"
                onClick={() => onSubmit(order)}
              >
                {t`保存`}
              </Form.Submit>
            )}
            <Button
              style={{ marginLeft: 8 }}
              onClick={handleCancel}
            >
              {t`取消`}
            </Button>
          </FormItem>
        </DrawerFooter>
      </Form>
    </>
  );
};
export default RsOrderForm;
